const { trafficSendData, mobileSendData } = require('./asyncHttp')
const dateFormat = require('dateformat')
const schedule = require("node-schedule")

const dateLabel = 'yyyy-mm-dd HH:MM:ss' // 时间格式
const scheduleRule = '30 */3 * * * *' // 定时任务格式 每隔3分

class SocketIo {
  constructor (io) {
    this.io = io
    this.socket = null
    this.socketNum = 0
    this.cityCode = null
  }

  into () {
    this.socket.on('join', ({ cityCode }) => {
      console.log(`有一个用户加入了查询的cityCode:${cityCode}, 开始调接口, 当前时间:${dateFormat(new Date(), dateLabel)}`)
      this.cityCode = cityCode
      this.getSocketData() // 今日默认调接口
      // this.setSchedule() // 执行定时任务
      this.socketNum = this.socketNum + 1
      if (this.socketNum === 1) {
          console.log(this.socketNum)
          this.setSchedule() // 执行定时任务
      }
    })
    //  监听城市切换
    this.socket.on('cityChange', ({ cityCode }) => {
      console.log(`城市切到cityCode:${cityCode}了, 开始调接口, 当前时间:${dateFormat(new Date(), dateLabel)}`)
      this.cityCode = cityCode
      this.getSocketData() // 今日默认调接口
    })

  }

  setSchedule () { // 定时任务
    console.log(`已开启定时任务:${dateFormat(new Date(), dateLabel)}`)
    schedule.scheduleJob(scheduleRule, () => {
      console.log(`定时任务执行完毕，当前时间：${dateFormat(new Date(), dateLabel)}`)
      this.getData()
    })
  }

  getSocketData () { // 获取数据并定向推送
      mobileSendData(this.cityCode, ( mobilePayMount, mobilePayCount, mobileCardCount, mapData, deviceData, sexData, areaData, ageData, averagePay, averagePayPie, busAveragePay, cityPay, cityMonthPay) => {
        console.log(`初始化移动大屏成功 当前时间: ${dateFormat(new Date(), dateLabel)}`)
        this.socket.emit('mobileData', JSON.stringify({ mobilePayMount, mobilePayCount, mobileCardCount, mapData, deviceData, sexData, areaData, ageData, averagePay, averagePayPie, busAveragePay, cityPay, cityMonthPay}))
      })
  }

  getData () { // 获取数据并广播
      mobileSendData(this.cityCode, ( mobilePayMount, mobilePayCount, mobileCardCount, mapData, deviceData, sexData, areaData, ageData, averagePay, averagePayPie, busAveragePay, cityPay, cityMonthPay) => {
          console.log(`定时返回移动成功 当前时间: ${dateFormat(new Date(), dateLabel)}`)
          this.io.sockets.emit('mobileData', JSON.stringify({ mobilePayMount, mobilePayCount, mobileCardCount, mapData, deviceData, sexData, areaData, ageData, averagePay, averagePayPie, busAveragePay, cityPay, cityMonthPay}))
      })
  }

  init () {
    this.io.on('connection', (socket) => { // 建立长连接
      this.socket = socket
      // 监听用户进入了
      this.into()
    })
  }
}

module.exports = {
  StartSocketIo: (io) => {
    new SocketIo(io).init()
  }
}
